package com.yan.composite;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("all")
public abstract class AbstractComposite extends AbstractNameable implements Tree<Nameable> {
    private List<Nameable> composites = new LinkedList<>();
    private String prefix = "|-";

    public AbstractComposite(String name) {
        super(name);
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public boolean isRoot() {
        return false;
    }

    @Override
    public void add(Nameable c) {
        composites.add(c);
    }

    @Override
    public void remove(Nameable c) {
        composites.remove(c);
    }

    @Override
    public Nameable getChild(int i) {
        return composites.get(i);
    }

    @Override
    public Nameable getChild(String name) {
        return composites.stream().filter(developer -> name.equals(developer.getName())).findAny().orElse(null);
    }

    @Override
    public Collection<Nameable> getChildren() {
        return composites;
    }

    @Override
    public void report() {
        if (isRoot()) {
            System.out.println(getPrefix() + getName());
        }
        getChildren().forEach(child -> {
            System.out.println("\t" + getPrefix() + child.getName());
            if (child instanceof AbstractComposite) {
                AbstractComposite abstractComposite = (AbstractComposite) child;
                abstractComposite.setPrefix("\t" + getPrefix());
                abstractComposite.report();
            }
        });
    }
}
